//维修工单
import React, { Component } from 'react';
import { Table, Button, Form, Card, Tabs, Modal ,Select,Col,Row} from 'antd';
import '@/assets/css/settings';
import { withRouter } from 'react-router-dom';
import BasicForm from "../../components_yyr/common/basicForm";
import { FileDown } from "../../components_yyr/commponent/File";
import Paging from "../../components_yyr/commponent/Paging";
import BasicConfirm from "../../components_yyr/common/basicConfirm";
import { openNotification } from '../../utils_yyr/action';
import * as Utils from '../../utils_yyr/action';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
import Zmage from 'react-zmage'
const {Option} = Select

const { TabPane } = Tabs;
class App extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false,//新增修改抽屉的显示与隐藏
		chooseData: {},
		drawerTitle: '',
		total: 0,
		formValues: {},
		cityData: [],
		mainFactoryList: [],
		selectedData: [],
		selectedKeys: [],
		wxz:[],
		visibleDispatch:false,
		UserList:[],pictureIdList:[],pictureIds:[]
	};
	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10,
			typeId:1,
			typeId1:'2&typeId=0',
			userId:localStorage.getItem('userId'),
			isApp:0,
			ssss:0,
			type:100
		});
		this.wxz()
		this.queryPageUser()
		// this.getInfo();
	}
	//初始化加载数据
	fetch = (data) => {
		let str = ''
		for(var key in data){
			if(key=='typeId1'){
				str += `&typeId=${data[key]}`
			}else
			if(data[key]||data[key]===0){
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({ loading: true })
		this.get(euqApplicationName + '/equipmentRepair/findEquipmentRepairList?'+str).then(res => {
			this.setState({
				loading: false,
				dataSource: res.data,
				total:res.total,
				formValues:data,
				selectedData: [],
				selectedKeys: [],

			});
		})
	} 
	wxz = () => {//维修组
		this.get(euqApplicationName + '/parameter_setting_public/queryTeamPageList?type=维修').then(res => {
		this.setState({
			 wxz: res.data,
		 });
		 })
	}; 
	getInfo = () => {
		this.post('/carrierPrice/mainFactoryList').then(res => this.setState({ mainFactoryList: res.data }))//主机厂
	}
	//   用户查询
	queryPageUser = () => {
		this.get(lotAuth2 + '/user/queryPageUser').then(res => {
			this.setState({
				UserList : res.data.data
			});
		})
	}	
	//表单查询
	filterSubmit = (values) => {
		console.log("表单查询=====", values)
		if(values.startTime_endTime && values.startTime_endTime.length==2){
			values.startTime = Utils.getDate(values.startTime_endTime[0]) + ' 00:00:00'
			values.endTime = Utils.getDate(values.startTime_endTime[1]) + ' 23:59:59'
		}
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		values.typeId1 = '2&typeId=0';
		values.typeId = 1;
		values.userId = localStorage.getItem('userId')
		values.isApp = 0
		values.ssss = 0
		values.type = 100
		this.fetch(values);
	};

	// 表格删除
	handleConfirm = (value, api, chooseData) => {
		console.log(this.state.selectedData)
		let str = ''
		for(var item of this.state.selectedData){
			str += item.id + ','
		}
		this.get(`${euqApplicationName}/equipmentRepair/deleteEquipmentRepair/${str.slice(0, str.length - 1)}/1`).then(res => {
			this.success();
			this.fetch({ ...this.state.formValues });
			this.setState({selectedKeys:[],selectedData:[]})
		});
	};

	handleConfirmInfo = (data) => {
		this.setState({
			selectedKeys: [],
			selectedData: []
		})
	}

	// 表格打印
	handlePrinting = (type, data) => {
		console.log("打印=====")
	}

	formList = () => {
		const formList = [
			{ type: "TIMEFRAME", label: "提出时间", field: "startTime_endTime", },
			{ type: "INPUT", label: "维修单号", field: "repairOrder", },
			{
				type: "SELECT", label: "维修状态", field: "statusIds", name: 'value',
				list: [{ id: 3, value: '待维修' }, { id: 4, value: '维修中' }, { id: 8, value: '已完成' }], valueField: 'id'
			},
			{
				type: "SELECT", label: "维修组", field: "repairTeamName", name: 'name',
				list: this.state.wxz, valueField: 'name'
			},
			// {
			// 	type: "SELECT", label: "相关性", field: "bxName", name: 'value',
			// 	list: [{ id: 1, value: '全部' }, { id: 2, value: '我维修' }], valueField: 'value'
			// }
		]
		return formList;
	};


	drawerFormList = data => {
		const { mainFactoryList } = this.state;
		const drawerFormList = [
			{ type: 'TITLE', label: '基本信息' },
			{ type: "INPUT", label: "维修单号", field: "repairOrderId", initialValue: data.repairOrderId, list: mainFactoryList },
			{ type: "INPUT", label: "设备编号", field: "sbbianhao", initialValue: data.sbbianhao },
			{ type: "INPUT", label: "设备名称", field: "harborOneTonPrice", initialValue: data.harborOneTonPrice, required: true },
			{ type: "INPUT", label: "规格型号", field: "ggxh", initialValue: data.ggxh },
			{ type: "TREESELECT", label: "所在部门", field: "doorMinimumPrice", initialValue: data.doorMinimumPrice, name: 'value', valueField: 'value', list: mainFactoryList.doorMinimumPrice },
			{ type: "TREESELECT", label: "设备类别", field: "sblb", initialValue: data.sblb, name: 'value', valueField: 'value', list: mainFactoryList.sblb },
			{ type: "INPUT", label: "设备位置", field: "doorOneHundredPrice", initialValue: data.doorOneHundredPrice },
			{ type: "BOTTOM", label: "选择设备", field: "doorMinimumPrice", initialValue: data.doorMinimumPrice },

			{ type: 'TITLE', label: '故障信息' },
			{ type: "DATE", label: "发生时间", field: "harborTwoHundredPrice", initialValue: data.harborTwoHundredPrice, list: mainFactoryList },
			{ type: "SELECT", label: "操作人", field: "people", initialValue: data.people, name: 'value', valueField: 'value', list: mainFactoryList.people },
			{ type: "SELECT", label: "设备部位", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TREESELECT", label: "故障类别", field: "gzlb", initialValue: data.gzlb, name: 'value', valueField: 'value', list: mainFactoryList.gzlb },
			{ type: "SELECT", label: "故障等级", field: "gzlevel", initialValue: data.gzlevel, name: 'value', valueField: 'value', list: mainFactoryList.gzlevel },
			{ type: "TEXTAREA", label: "备注描述", field: "remarks", initialValue: data.remarks },

			{ type: 'TITLE', label: '处理情况' },
			{ type: "SELECT", label: "故障原因", field: "uniqueAddress", initialValue: data.uniqueAddress, name: 'value', valueField: 'value', list: mainFactoryList.uniqueAddress },
			{ type: "SELECT", label: "维修组", field: "wxGroup", initialValue: data.wxGroup, people: false, name: 'value', valueField: 'value', list: mainFactoryList.wxGroup },
			{ type: "SELECT", label: "维修状态", field: "wxStauts", initialValue: data.wxStauts, name: 'value', valueField: 'value', list: mainFactoryList.wxStauts },
			{ type: "SELECT", label: "维修级别", field: "wxjb", initialValue: data.wxjb, name: 'value', valueField: 'value', list: mainFactoryList.wxjb },
			{ type: "SELECT", label: "维修类别", field: "wxlb", initialValue: data.wxlb },
			{ type: "SELECT", label: "紧急程度", field: "harborOneHundredPrice", initialValue: data.harborOneHundredPrice, name: 'value', valueField: 'value', list: mainFactoryList.harborOneHundredPrice },
			{
				type: "CHECKBOX", label: "是否停机", field: "harborTwoHundredPrice", initialValue: data.harborTwoHundredPrice,
				name: 'value',
				list: [{ label: '重点设备', value: '1' }],
				valueField: 'value'
			},
			{ type: "DATE", label: "停机时长", field: "remarks", initialValue: data.remarks },
			{ type: "DATE", label: "开始时间", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "DATE", label: "结束时间", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "INPUT", label: "维修用时", field: "wxTiem", initialValue: data.harborMinimumPrice },
			{ type: "INPUTNUMBER", label: "维修费用", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TEXTAREA", label: "外委单位", field: "remarks", initialValue: data.remarks },
			{ type: "TEXTAREA", label: "工作描述", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },

			{ type: "TITLE", label: "维修工作量", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "BOTTOM", label: "增加人员", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TABLE", label: "", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },

			{ type: "TITLE", label: "更换备件", field: "remarks", initialValue: data.remarks },
			{ type: "BOTTOM", label: "选择备件", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TABLE", label: "", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice }
		];
		return drawerFormList;
	};

	// 提交modal
	handleSubmit = data => {
		const { dataSource, chooseData } = this.state;
		let key = chooseData.key;
		let newDataSource = dataSource;
		let index = newDataSource.findIndex((value) => value.key == key);
		if (key) {
			console.log("******修改******")
			for (let j of newDataSource) {
				if (j.key == key) {
					newDataSource[index] = { ...newDataSource[index], ...data }
				}
			}
		} else {
			console.log("******添加******")
			newDataSource.push(data);
		}
		this.setState({
			dataSource: newDataSource,
		})
		this.onClose();


		// 注释
		// const id = this.state.chooseData && this.state.chooseData.id;
		// if (id) {
		// 	data = Object.assign({}, data, { id: id });
		// 	data.updateId = localStorage.getItem('userId');
		// } else {
		// 	data.createId = localStorage.getItem('userId');
		// }
		// this.post('/airCargo/addAirCargo', { data }).then(res => {
		// 	this.success();
		// 	this.fetch({ ...this.state.formValues });
		// 	this.onClose();
		// })

	};

	// 打开modal，判断是修改还是新增 0新增 1修改
	handleModal = (type, data) => {
		if (type) {
			this.setState({
				drawerTitle: "修改",
				drawerVisible: true,
				chooseData: data
			});
		} else {
			this.setState({
				drawerTitle: "新增",
				drawerVisible: true,
			});
		}
	};


	onClose = () => {
		this.setState({
			drawerVisible: false,
			chooseData: {}
		});
		this.modalRef.props.form.resetFields();
	}

	dispatch = () => {
		let data = this.state.selectedData
		if(data.length===0){
			openNotification("warning",'请选择要派工单据!')
			return;
		}
		for(var item of data){
			if(item.majorStaff){
				openNotification("warning",'没有人维修的单据才能派工！')
				return;
			}
		}
		this.setState({
			visibleDispatch:true
		})
	}
	handleOk = () => {
		this.props.form.validateFields(['majorStaffs','repairTeamId',],(err,values)=>{
			if(!err){
				if(values['majorStaffs'] || values['repairTeamId'] ){
					let selectedData = this.state.selectedData
					let selectedKeys = []
					for(var item of selectedData){
						selectedKeys.push(item.treatmentId)
					}
					values.ids = selectedKeys
					console.log(values)
					let equipmentRepairWorkAddDTOList = []
					values['majorStaffs'].forEach(item=>{
						for(var itemss of this.state.UserList){
							if(itemss.userId==item){
								equipmentRepairWorkAddDTOList.push({
									personId:item,
									personName:itemss.userName
								})
							}
						}
					})
					for(let i in equipmentRepairWorkAddDTOList){
						if(i==0){
							equipmentRepairWorkAddDTOList[i].perType = 0
						}else{
							equipmentRepairWorkAddDTOList[i].perType = 1
						}
					}
					values.equipmentRepairWorkAddDTOList = equipmentRepairWorkAddDTOList
					this.post(euqApplicationName + '/equipmentRepair/dispatch',{data:values}).then(res => {
						this.success()
						this.handleCancel()
					})
				}
			}
		})
	}
	handleCancel = () => {
		this.setState({visibleDispatch:false,selectedKeys:[],selectedData:[]})
		this.fetch({...this.state.formValues})
		this.props.form.resetFields();
	}
	test = (event) => {
		console.log(event)
		this.props.form.resetFields('majorStaffs')
		if(event==undefined){
			this.queryPageUser()
			return
		}else{
			this.props.form.resetFields('majorStaffs')
			const {wxz} = this.state
			wxz.forEach((item)=>{
				return item.id == event && this.setState({UserList:item.userIdList})
			})
		}
		
	}
	onRowClick = (record) => {
		if(record.imgPath && record.imgPath.length>0){
			this.setState({pictureIdList:record.imgPath,pictureIds:record.pictureIdList})
		}else{
			this.setState({pictureIdList:[],pictureIds:[]})
		}
		this.setState({selectedKeys:[record.id],selectedData:[record]})
	}
	render() {
		const columns = [
			{
				title: '操作', width: 100, fixed:'left',
				render: (text, record) => {
					return record.status===8 ? <span><a href onClick={() => this.props.history.push('/RepairWorkOrderDetails/'+record.treatmentId)}>详情</a></span> : <span><a href onClick={() => this.props.history.push('/DetailRepairWorkOrder/'+record.treatmentId)}>执行维修</a></span>
				}
			},
			{ title: '维修单号', width: 150, dataIndex: 'equRepairCode', fixed:'left'},
			{ title: '状态', width: 150, dataIndex: 'status',fixed:'left' ,
				render:(text,record)=>{
					if( text===3 || text===9 || text===5 || text===6 || text===7){
						return '待维修'
					}else if(text===10 || text===4){
						return '维修中'
					}
					else{
						return text===8 ? '已完成' : ''
						// return text===1 ? '待审核' : text===2 ? '审核中' : text===4 ? '维修中' : text===5 ? '列入计划' : text===6 ? '待验证' : text===7 ? '驳回' : text===8 ? '已完成' : text===10 ? '暂停中' : ''
					}
				}
		},
			{ title: '维修组', width: 150, dataIndex: 'teamName', fixed:'left'},
			{ title: '主修人员', width: 150, dataIndex: 'majorStaff', fixed:'left'},
			{ title: '辅修人员', width: 100, dataIndex: 'minorStaff', fixed:'left' },
			{ title: '提出时间', width: 150, dataIndex: 'createTime',  fixed:'left'},
			{ title: '维修开始时间', width: 150, dataIndex: 'startTime', fixed:'left'},
			{ title: '维修结束时间', width: 150, dataIndex: 'endTime', fixed:'left'},
			{ title: '设备名称', width: 150, dataIndex: 'equName', fixed:'left'},
			{ title: '使用部门', width: 150, dataIndex: 'deptName', },
			{ title: '设备位置', width: 150, dataIndex: 'equLocation', },
			{ title: '故障描述', width: 150, dataIndex: 'faultDescription', },
			{ title: '报修人', width: 100, dataIndex: 'repairMan', },
			{ title: '报修时间', width: 100, dataIndex: 'time', },
			// { title: '维修用时', width: 100, dataIndex: 'repairTime', },
			{ title: '设备编号', width: 100, dataIndex: 'equCode', },
			{ title: '规格型号', width: 100, dataIndex: 'equSpecsModel', },
			{ title: '维修工时', width: 100, dataIndex: 'wastedTime', },
			{ title: '停机时间', width: 100, dataIndex: 'stopDuration', },
			{ title: '故障类别', width: 100, dataIndex: 'faultTypeName', },
			{ title: '维修类别', width: 100, dataIndex: 'repairTypeName', },
			{ title: '维修级别', width: 100, dataIndex: 'repairLevelName', },
			{ title: '设备类型', width: 100, dataIndex: 'equType', },

		];

		const columns1 = [
			{ title: '查看', width: 100, dataIndex: 'sblx1', },
			{ title: '文件名', width: 100, dataIndex: 'sblx2', },
			{ title: '文档类型', width: 100, dataIndex: 'sblx3', },
			{ title: '上传时间', width: 100, dataIndex: 'sblx4', },
			{ title: '上传者', width: 100, dataIndex: 'sblx5', },
			{ title: '文件类型', width: 100, dataIndex: 'sblx6', },
			{ title: '文档大小', width: 100, dataIndex: 'sblx7', },
			{ title: '文件下载', width: 100, dataIndex: 'sblx8', },
		]

		const { chooseData, drawerVisible, drawerTitle, dataSource, loading, total, formValues, selectedData, selectedKeys ,wxz,UserList,pictureIds} = this.state;

		const drawerProps = {
			onRef: (ref) => this.modalRef = ref, visible: drawerVisible, width: 700, drawerFormList: this.drawerFormList(chooseData),
			submit: this.handleSubmit, onClose: this.onClose, title: drawerTitle
		}
		//选择框
		const rowSelection = {
			selectedRowKeys: selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedData: selectedRows,
					selectedKeys: selectedRowKeys
				})
			},
			getCheckboxProps: record => ({
				disabled: record.name === 'Disabled User',
				name: record.name
			})
		};
		const { getFieldDecorator}=this.props.form
		return (
			<div className="shadow-radius">
				<Card><BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={(ref) => this.child = ref} /></Card>

				<Tabs tabBarExtraContent={
					<div className="buttonList">
						{/* <Button icon="plus" onClick={() => this.handleModal(0, {})} type="primary"> 快速工单</Button> */}
						<Button icon="plus" onClick={() =>{this.props.history.push('/AddRepairWorkOrder/new')}} type="primary"> 快速工单 </Button>

						{/* <BasicConfirms title="查看评分" api={1} icon="plus" button={true} buttonName="评分" data={selectedData} handleConfirmInfo={ this.handleConfirmInfo}/> */}
						<Button icon="plus"  onClick={()=>{this.dispatch()}} type="primary"> 派工 </Button>
						<BasicConfirm title="确认删除?" api={1} icon="delete" button={true} buttonName="删除"  handleConfirm={this.handleConfirm} data={selectedData}/>
						<FileDown fileName="维修工单列表" buttonName="导出" method="post" apiPath={euqApplicationName + "/equipmentRepair/exportEquipmentRepairListExcel"} data={{...this.state.formValues,ids:selectedKeys,typeId:[1,0,2],statusIds:this.state.formValues.statusIds ? [this.state.formValues.statusIds] : []}} />
						{/* <Button icon="delete" onClick={() => this.handlePrinting(0, {})} type="primary">{' '} 打印</Button> */}
					</div>
				}>
					<TabPane tab='维修工单' key='1'>
						<Table columns={columns} rowSelection={rowSelection} rowKey={(record) => record.id} dataSource={dataSource} pagination={false} loading={loading}  scroll={{ x: 1500, y: 600 }}  onRowClick={(record)=>{this.onRowClick(record)}}/>
						<Paging total={total} formValues={formValues} fetch={(pager) => this.fetch(pager)} />
					</TabPane>
				</Tabs>
				<Tabs>
					<TabPane tab="故障图片" key="2">
						<div style={{ width: '100%' ,marginLeft:15,display:this.state.selectedKeys.length===1 ? 'inline-block' : 'none'}} onChange={this.onChange}>
							<Row gutter={20} style={{width:1200}}>
								{this.state.pictureIdList && this.state.pictureIdList.length>0 ? this.state.pictureIdList.map((ii)=>{
									return  <Col span={4}>
												<Zmage src={ii} style={{width:150,height:120,}}/>
											</Col>
								}) : ' 暂无图片'}
							</Row>
						</div>

					</TabPane>
				</Tabs>


				{/* <BasicDrawers	{...drawerProps} /> */}
				<Modal
				title="派工"
				visible={this.state.visibleDispatch}
				onOk={this.handleOk}
				onCancel={this.handleCancel}
				okText="确认"
				cancelText="取消"
				>
					<Form>
						<Form.Item label="维修组">
							{getFieldDecorator('repairTeamId',{ rules: [{	required: true,	message: '请选择维修组'}]})(<Select allowClear placeholder='请输入维修组' onChange={this.test}>
									{wxz.map(item=><Option value={item.id}>{item.name}</Option>)}
							</Select>)}
						</Form.Item>
						<Form.Item label="维修人员">
							{getFieldDecorator('majorStaffs',{ rules: [{	required: true,	message: '请选择维修人员'}]})(<Select mode="multiple" allowClear placeholder='请输入维修人员'>
								{UserList.map(item=><Option value={item.userId}>{item.userName}</Option>)}
							</Select>)}
						</Form.Item>
					</Form>
				</Modal>

			</div>
		);
	}
}
export default Form.create()(withRouter(App));